package com.example.barrage.controller;

import com.example.barrage.model.BarrageMessage;
import com.example.barrage.service.BarrageProducerService;
import com.example.barrage.service.SensitiveWordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@Controller
public class BarrageController {

    private static final Logger logger = LoggerFactory.getLogger(BarrageController.class);

    @Autowired
    private BarrageProducerService barrageProducerService;
    
    @Autowired
    private SensitiveWordService sensitiveWordService;

    /**
     * 主页，返回弹幕页面
     */
    @GetMapping("/")
    public String index(Model model) {
        String userId = UUID.randomUUID().toString();
        model.addAttribute("userId", userId);
        logger.info("为用户生成弹幕页面: {}", userId);
        return "barrage";
    }

    /**
     * 发送弹幕消息的API接口
     */
    @PostMapping("/send")
    @ResponseBody
    public String sendBarrage(@RequestBody BarrageMessage barrageMessage) {
        try {
            logger.info("收到弹幕消息请求: 用户ID={}, 内容={}", 
                barrageMessage.getUserId(), barrageMessage.getContent());
            
            // 检查并过滤敏感字符
            if (sensitiveWordService.containsSensitiveWords(barrageMessage.getContent())) {
                logger.warn("弹幕消息包含敏感词: {}", barrageMessage.getContent());
                return "error: 消息包含敏感字符，发送失败";
            }
            
            // 设置用户ID（如果未设置）
            if (barrageMessage.getUserId() == null || barrageMessage.getUserId().isEmpty()) {
                barrageMessage.setUserId(UUID.randomUUID().toString());
                logger.debug("为弹幕消息生成用户ID: {}", barrageMessage.getUserId());
            }

            // 设置默认用户名（如果未设置）
            if (barrageMessage.getUsername() == null || barrageMessage.getUsername().isEmpty()) {
                barrageMessage.setUsername("User-" + barrageMessage.getUserId().substring(0, 8));
                logger.debug("为弹幕消息生成用户名: {}", barrageMessage.getUsername());
            }

            // 发送到RocketMQ
            barrageProducerService.sendBarrageMessage(barrageMessage);

            logger.info("弹幕消息发送成功: 用户ID={}, 用户名={}, 内容={}", 
                barrageMessage.getUserId(), barrageMessage.getUsername(), barrageMessage.getContent());
            return "success";
        } catch (Exception e) {
            logger.error("发送弹幕消息失败", e);
            return "error: " + e.getMessage();
        }
    }
}